package plugin

import (
	"context"
	"database/sql"
	"net/http"
	"sync"

	"gitee.com/mkwchecking/k-scaffold/config"
	"gitee.com/mkwchecking/k-scaffold/pkg/rely/log"
	"gitee.com/mkwchecking/k-scaffold/pkg/rely/trace"
	kconfig "github.com/go-kratos/kratos/v2/config"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/spf13/cobra"
	"gorm.io/gorm"
)

func NewPlugins(cmd *cobra.Command) (*Plugins, error) {
	p := &Plugins{
		_lock: sync.Mutex{},
	}
	err := p.initContext(cmd)
	return p, err
}

type Plugins struct {
	ctx    context.Context
	_lock  sync.Mutex
	source kconfig.Config

	_gdb *gorm.DB

	_sqldb *sql.DB

	_trace *trace.Trace

	_log *log.Logger

	_httpSvr    transport.Server
	_httpEngine http.Handler

	_grpcSvr transport.Server
}

func (p *Plugins) Ctx() context.Context { return p.ctx }

func (p *Plugins) initContext(cmd *cobra.Command) error {

	ctx, src, _, err := InitConfig(cmd.Context(), cmd)
	if err != nil {
		return err
	}
	p.source = src
	p.ctx = ctx

	logger, err := p.GetLogger()
	if err != nil {
		return err
	}

	return WatchConfig(logger, src, config.Get())

}
